package com.gitee.apecome.core.remote.net.netty.server;

import com.gitee.apecome.core.remote.ApeRpcProviderFactory;
import com.gitee.apecome.core.remote.bean.ApeRpcRequest;
import com.gitee.apecome.core.remote.bean.ApeRpcResponse;
import com.gitee.apecome.core.remote.code.NettyDecoder;
import com.gitee.apecome.core.remote.code.NettyEncoder;
import com.gitee.apecome.core.remote.code.serialize.impl.HessianSerializer;
import com.gitee.apecome.core.remote.net.netty.server.handler.NettyRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer implements Server {

    private Integer port;

    public NettyServer(Integer port) {
        this.port = port;
    }

    public static NettyServer bulidServer(Integer port) {
        return new NettyServer(port);
    }

    public void run() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new NettyDecoder(ApeRpcRequest.class, HessianSerializer.newInstance()))
                                    .addLast(new NettyEncoder(ApeRpcResponse.class, HessianSerializer.newInstance()))
                                    .addLast(new NettyRequestHandler(ApeRpcProviderFactory.newInstance()));
                        }
                    });
            // bind
            ChannelFuture future = sb.bind().sync();
            // wait util stop
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                workGroup.shutdownGracefully().sync();
                bossGroup.shutdownGracefully().sync();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void start() {
        Thread thread = new Thread(() -> {
            run();
        });
        //thread.setDaemon(true);
        thread.start();
        System.out.println("server netty port=" + port + "启动");
    }
}
